package net.hserver.apm;


import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import net.hserver.apm.common.DataConfig;
import net.hserver.apm.config.MongodbConfig;
import org.bson.conversions.Bson;
import cn.hserver.core.ioc.annotation.Autowired;
import cn.hserver.core.ioc.annotation.Bean;
import cn.hserver.core.ioc.annotation.Task;
import cn.hserver.core.server.HumClient;
import cn.hserver.core.server.context.ConstConfig;
import cn.hserver.core.server.context.HumMessage;

import java.time.LocalDate;
import java.time.ZoneOffset;

@Bean
public class DataTask {

    @Autowired
    private MongoClient mongoClient;

    public static Long runTime = System.currentTimeMillis();

    /**
     * 30天前的日志数据清除
     */
    public static Integer day = 30;

    public static boolean switchBoolean = true;


    @Task(name = "checkConnect", time = "10000")
    public void connect() {
        HumClient.sendMessage(new HumMessage(DataConfig.APM_LIVE, DataConfig.APM_LIVE));
    }

    /**
     * 每天中午执行
     */
    @Task(name = "清除历史数据", time = "0 0 12 * * ?")
    public void hisData() {
        if (switchBoolean) {
            runTime = System.currentTimeMillis();
            LocalDate now = LocalDate.now();
            LocalDate localDate = now.minusDays(day);
            long mili = localDate.atStartOfDay().toInstant(ZoneOffset.of("+8")).toEpochMilli();
            MongoDatabase database = mongoClient.getDatabase(MongodbConfig.DATA_BASE);
            Bson time = Filters.lt("time", mili);
            database.getCollection("linkInfo").deleteMany(time);
            database.getCollection("requestInfo").deleteMany(time);
            database.getCollection("logInfo").deleteMany(time);
            database.getCollection("serverInfo").deleteMany(time);
            database.getCollection("sqlInfo").deleteMany(time);
        }
    }

}
